﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using FBroSharp;
using FBroSharp.Lib;
using FBroSharp.Value;
using FBroSharp.DataType;

namespace ProxySwitchBrowser
{
    public partial class Form1 : Form
    {
        private const string BROWSER_USER_FLAG = "proxy_browser";
        private IFBroSharpBrowser _browser;
        private List<ProxyInfo> _proxyList = new List<ProxyInfo>();
        private int _currentProxyIndex = -1;
        private bool _autoSwitchEnabled = false;
        private Timer _autoSwitchTimer;

        public Form1()
        {
            InitializeComponent();
            InitializeProxyList();
            InitializeAutoSwitchTimer();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            CreateBrowser();
        }

        /// <summary>
        /// 创建浏览器实例
        /// </summary>
        private void CreateBrowser()
        {
            try
            {
                // 创建窗口信息（嵌入式浏览器）
                FBroSharpWindowsInfo windowsInfo = new FBroSharpWindowsInfo
                {
                    parent_window = panelBrowser.Handle,  // 嵌入到Panel中
                    x = 0,
                    y = 0,
                    width = panelBrowser.Width,
                    height = panelBrowser.Height,
                    window_name = "代理切换浏览器"
                };

                // 创建浏览器事件处理器
                BrowserEvent browserEvent = new BrowserEvent(this);

                // 创建浏览器
                bool success = FBroSharpControl.CreatBrowser(
                    "https://ipinfo.io",  // 显示IP信息的网站
                    windowsInfo,
                    default,  // FBroSharpBrowserSetting
                    null,     // FBroSharpRequestContext
                    null,     // FBroSharpDictionaryValue
                    browserEvent,
                    default,  // FBroSharpEventDisableControl (struct, 使用default)
                    BROWSER_USER_FLAG
                );

                if (success)
                {
                    UpdateStatus("浏览器创建中...");
                }
                else
                {
                    MessageBox.Show("浏览器创建失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建浏览器时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 浏览器创建完成回调
        /// </summary>
        public void OnBrowserCreated(IFBroSharpBrowser browser)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnBrowserCreated(browser)));
                return;
            }

            _browser = browser;
            UpdateStatus("浏览器已就绪");
            Console.WriteLine($"✅ 浏览器创建成功，ID: {browser.GetIdentifier()}");
        }

        /// <summary>
        /// 地址变更回调
        /// </summary>
        public void OnAddressChanged(string url)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnAddressChanged(url)));
                return;
            }

            txtUrl.Text = url;
        }

        /// <summary>
        /// 标题变更回调
        /// </summary>
        public void OnTitleChanged(string title)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnTitleChanged(title)));
                return;
            }

            this.Text = $"代理切换浏览器 - {title}";
        }

        /// <summary>
        /// 加载状态变更回调
        /// </summary>
        public void OnLoadingStateChanged(bool isLoading, bool canGoBack, bool canGoForward)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnLoadingStateChanged(isLoading, canGoBack, canGoForward)));
                return;
            }

            btnRefresh.Enabled = !isLoading;
            btnBack.Enabled = canGoBack;
            btnForward.Enabled = canGoForward;

            if (isLoading)
            {
                UpdateStatus("正在加载...");
            }
        }

        /// <summary>
        /// 加载开始回调
        /// </summary>
        public void OnLoadStart(string url)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnLoadStart(url)));
                return;
            }

            UpdateStatus($"开始加载: {url}");
        }

        /// <summary>
        /// 加载完成回调
        /// </summary>
        public void OnLoadEnd(string url, int httpStatusCode)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnLoadEnd(url, httpStatusCode)));
                return;
            }

            UpdateStatus($"加载完成 (HTTP {httpStatusCode})");
            
            // 加载完成后，获取IP信息
            Task.Run(() => GetIPInfo());
        }

        /// <summary>
        /// 加载错误回调
        /// </summary>
        public void OnLoadError(string url, string errorText)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnLoadError(url, errorText)));
                return;
            }

            UpdateStatus($"加载失败: {errorText}");
        }

        /// <summary>
        /// 更新状态栏
        /// </summary>
        public void UpdateStatus(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateStatus(message)));
                return;
            }

            lblStatus.Text = message;
        }

        /// <summary>
        /// 窗体调整大小时调整浏览器大小
        /// </summary>
        private void Form1_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        /// <summary>
        /// Panel调整大小时调整浏览器大小
        /// </summary>
        private void panelBrowser_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        /// <summary>
        /// 调整嵌入式浏览器大小
        /// </summary>
        private void ResizeEmbeddedBrowser()
        {
            try
            {
                if (_browser != null && _browser.IsValid)
                {
                    _browser.MoveWindow(0, 0, panelBrowser.Width, panelBrowser.Height, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"调整浏览器大小失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 导航到URL
        /// </summary>
        private void btnGo_Click(object sender, EventArgs e)
        {
            NavigateToUrl(txtUrl.Text);
        }

        /// <summary>
        /// 导航到指定URL
        /// </summary>
        private void NavigateToUrl(string url)
        {
            try
            {
                if (_browser == null || !_browser.IsValid)
                {
                    MessageBox.Show("浏览器实例无效！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (string.IsNullOrWhiteSpace(url))
                {
                    return;
                }

                // 如果URL不包含协议，自动添加https://
                if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                {
                    url = "https://" + url;
                }

                var mainFrame = _browser.GetMainFrame();
                if (mainFrame != null && mainFrame.IsValid)
                {
                    mainFrame.LoadURL(url);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导航失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新页面
        /// </summary>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                if (_browser != null && _browser.IsValid)
                {
                    _browser.Reload();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"刷新失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 后退
        /// </summary>
        private void btnBack_Click(object sender, EventArgs e)
        {
            try
            {
                if (_browser != null && _browser.IsValid && _browser.CanGoBack())
                {
                    _browser.GoBack();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"后退失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 前进
        /// </summary>
        private void btnForward_Click(object sender, EventArgs e)
        {
            try
            {
                if (_browser != null && _browser.IsValid && _browser.CanGoForward())
                {
                    _browser.GoForward();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"前进失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 初始化代理列表
        /// </summary>
        private void InitializeProxyList()
        {
            _proxyList.Add(new ProxyInfo { Name = "无代理", Type = "direct", Url = "" });
            _proxyList.Add(new ProxyInfo { Name = "HTTP 代理 1", Type = "http", Url = "http://127.0.0.1:7897" });
            _proxyList.Add(new ProxyInfo { Name = "HTTP 代理 2", Type = "http", Url = "http://127.0.0.1:7897" });
            _proxyList.Add(new ProxyInfo { Name = "SOCKS5 代理 1", Type = "socks5", Url = "socks5://127.0.0.1:7897" });

            UpdateProxyListBox();
        }

        /// <summary>
        /// 更新代理列表显示
        /// </summary>
        private void UpdateProxyListBox()
        {
            lstProxyList.Items.Clear();
            for (int i = 0; i < _proxyList.Count; i++)
            {
                var proxy = _proxyList[i];
                string display = $"{proxy.Name} - {proxy.Type.ToUpper()}";
                if (!string.IsNullOrEmpty(proxy.Url))
                {
                    display += $" - {proxy.Url}";
                }
                lstProxyList.Items.Add(display);
            }

            if (_currentProxyIndex >= 0 && _currentProxyIndex < lstProxyList.Items.Count)
            {
                lstProxyList.SelectedIndex = _currentProxyIndex;
            }
        }

        /// <summary>
        /// 设置代理
        /// </summary>
        private void btnSetProxy_Click(object sender, EventArgs e)
        {
            if (lstProxyList.SelectedIndex < 0)
            {
                MessageBox.Show("请先选择一个代理服务器！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            SetProxy(lstProxyList.SelectedIndex);
        }

        /// <summary>
        /// 设置指定索引的代理
        /// </summary>
        private void SetProxy(int index)
        {
            try
            {
                if (_browser == null || !_browser.IsValid)
                {
                    MessageBox.Show("浏览器实例无效！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var proxy = _proxyList[index];
                _currentProxyIndex = index;

                if (proxy.Type == "direct")
                {
                    // 清除代理
                    _browser.ClearProxy();
                    UpdateStatus("已清除代理");
                    lblCurrentProxy.Text = "当前代理: 无代理";
                }
                else if (proxy.Type == "socks5")
                {
                    // SOCKS5代理需要VIP功能
                    var vipControl = _browser.GetVIPControl();
                    if (vipControl != null && vipControl.IsValid)
                    {
                        var advancedControl = vipControl.GetAdvancedControl();
                        if (advancedControl != null)
                        {
                            advancedControl.SetProxy(proxy.Url, "", "", true);
                            UpdateStatus($"已设置SOCKS5代理: {proxy.Url}");
                            lblCurrentProxy.Text = $"当前代理: {proxy.Name}";
                        }
                        else
                        {
                            MessageBox.Show("无法获取高级控制器，SOCKS5代理设置失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("SOCKS5代理需要VIP授权！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
                else
                {
                    // HTTP/HTTPS代理
                    _browser.SetProxy(proxy.Url);
                    UpdateStatus($"已设置{proxy.Type.ToUpper()}代理: {proxy.Url}");
                    lblCurrentProxy.Text = $"当前代理: {proxy.Name}";
                }

                // 刷新页面使代理生效
                Task.Delay(500).ContinueWith(t =>
                {
                    if (InvokeRequired)
                    {
                        Invoke(new Action(() => _browser.Reload()));
                    }
                    else
                    {
                        _browser.Reload();
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"设置代理失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 添加代理
        /// </summary>
        private void btnAddProxy_Click(object sender, EventArgs e)
        {
            using (var dialog = new ProxyEditDialog())
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    _proxyList.Add(dialog.ProxyInfo);
                    UpdateProxyListBox();
                    UpdateStatus($"已添加代理: {dialog.ProxyInfo.Name}");
                }
            }
        }

        /// <summary>
        /// 删除代理
        /// </summary>
        private void btnRemoveProxy_Click(object sender, EventArgs e)
        {
            if (lstProxyList.SelectedIndex <= 0) // 不允许删除"无代理"
            {
                MessageBox.Show("请选择要删除的代理（无代理项不可删除）！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            int index = lstProxyList.SelectedIndex;
            var proxy = _proxyList[index];

            if (MessageBox.Show($"确定要删除代理 '{proxy.Name}' 吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                _proxyList.RemoveAt(index);
                UpdateProxyListBox();
                UpdateStatus($"已删除代理: {proxy.Name}");

                if (_currentProxyIndex == index)
                {
                    _currentProxyIndex = -1;
                }
            }
        }

        /// <summary>
        /// 测试代理连接
        /// </summary>
        private void btnTestProxy_Click(object sender, EventArgs e)
        {
            NavigateToUrl("https://ipinfo.io");
        }

        /// <summary>
        /// 获取IP信息
        /// </summary>
        private async Task GetIPInfo()
        {
            try
            {
                await Task.Delay(2000); // 等待页面加载完成

                if (_browser == null || !_browser.IsValid)
                    return;

                var mainFrame = _browser.GetMainFrame();
                if (mainFrame == null || !mainFrame.IsValid)
                    return;

                // 执行JavaScript获取IP信息
                string script = @"
                    (function() {
                        try {
                            var preElements = document.getElementsByTagName('pre');
                            if (preElements.length > 0) {
                                return preElements[0].innerText;
                            }
                            return 'IP信息加载中...';
                        } catch(e) {
                            return '获取IP信息失败';
                        }
                    })();
                ";

                // 注意：这里使用同步方式获取结果
                // FBroSharp的ExecuteJavaScript是异步的，需要通过回调获取结果
                // 这里简化处理，直接显示提示
                if (InvokeRequired)
                {
                    Invoke(new Action(() => UpdateIPInfo("请查看浏览器页面获取IP信息")));
                }
                else
                {
                    UpdateIPInfo("请查看浏览器页面获取IP信息");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取IP信息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新IP信息显示
        /// </summary>
        private void UpdateIPInfo(string info)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateIPInfo(info)));
                return;
            }

            txtIPInfo.Text = info;
        }

        /// <summary>
        /// 初始化自动切换定时器
        /// </summary>
        private void InitializeAutoSwitchTimer()
        {
            _autoSwitchTimer = new Timer();
            _autoSwitchTimer.Interval = 60000; // 默认60秒
            _autoSwitchTimer.Tick += AutoSwitchTimer_Tick;
        }

        /// <summary>
        /// 自动切换定时器事件
        /// </summary>
        private void AutoSwitchTimer_Tick(object sender, EventArgs e)
        {
            SwitchToNextProxy();
        }

        /// <summary>
        /// 切换到下一个代理
        /// </summary>
        private void SwitchToNextProxy()
        {
            if (_proxyList.Count <= 1)
                return;

            _currentProxyIndex++;
            if (_currentProxyIndex >= _proxyList.Count)
            {
                _currentProxyIndex = 0;
            }

            SetProxy(_currentProxyIndex);
        }

        /// <summary>
        /// 启用/禁用自动切换
        /// </summary>
        private void chkAutoSwitch_CheckedChanged(object sender, EventArgs e)
        {
            _autoSwitchEnabled = chkAutoSwitch.Checked;

            if (_autoSwitchEnabled)
            {
                int interval = (int)numSwitchInterval.Value * 1000;
                _autoSwitchTimer.Interval = interval;
                _autoSwitchTimer.Start();
                UpdateStatus($"已启用自动切换，间隔 {numSwitchInterval.Value} 秒");
            }
            else
            {
                _autoSwitchTimer.Stop();
                UpdateStatus("已禁用自动切换");
            }

            numSwitchInterval.Enabled = !_autoSwitchEnabled;
        }

        /// <summary>
        /// 窗体关闭时清理资源
        /// </summary>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            try
            {
                _autoSwitchTimer?.Stop();
                _autoSwitchTimer?.Dispose();

                if (_browser != null && _browser.IsValid)
                {
                    _browser.CloseBrowser(true, false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"关闭浏览器时出错: {ex.Message}");
            }

            base.OnFormClosing(e);
        }
    }

    /// <summary>
    /// 代理信息类
    /// </summary>
    public class ProxyInfo
    {
        public string Name { get; set; }
        public string Type { get; set; } // direct, http, https, socks5
        public string Url { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }
}
